<template>
  <div class="label-tree" v-loading="loading">
    <el-input
        class="filter-text"
        placeholder="请输入关键字进行查询"
        prefix-icon="el-icon-search"
        v-if="isShowCheckbox"
        v-model="filterText">
    </el-input>
    <el-tree :class="[{'edit-program' : treeData[0].isEdit}, {'edit-diy' : treeData[1].isEdit}]" ref="tree" :data="treeData" :props="{ label: 'name', children: 'tagList' }" :show-checkbox="isShowCheckbox" :filter-node-method="filterNode" node-key="id" highlight-current :default-expanded-keys="[1, 2]" :default-expand-all="false" :expand-on-click-node="false"  @check="addLabel">
            <span class="custom-tree-node" slot-scope="{ node, data, $index }">
              <label :title="node.label" v-if="node.level === 3" :class="[{'label-disable' : data.status === 2&&typeStr!='typePage'}]"><router-link :to="{query: {...$route.query, labelId: data.id, type: 'label'}}">{{ node.label }}</router-link></label>
<!--              <label :title="node.label" v-else :class="[{'label-disable' : data.status !== 1 && node.level === 2 &&typeStr!='typePage'}]">{{ node.label }}<span v-if="node.level === 2 && data.tagList.length !== 0">&nbsp({{typeStr=='typePage'?data.tierList.length:data.tagList.length}})</span></label>-->
              <label :title="node.label" v-else>{{ node.label }}<span v-if="node.level === 2 && data.tagList.length !== 0">&nbsp({{typeStr=='typePage'?data.tierList.length:data.tagList.length}})</span></label>
              <span class="operation select-num" v-if="isShowCheckbox">
                <el-badge v-if="node.level === 1" :value="selectNum" type="primary">已选</el-badge>
              </span>
              <span class="operation" v-else>
                <template v-if="node.level === 1">
                  <el-button type="text" size="mini" @click="() => onOperationType('edit', data)">{{ data.isEdit ? '取消' : '编辑' }}</el-button>
                  <el-button type="text" size="mini" @click="() => onOperationType('add', data)">新增分类</el-button>
                </template>
                <template v-else-if="node.level === 2">
                  <el-button type="text" size="mini" @click="() => onOperationType('rename', data)">重命名</el-button>
                  <el-button type="text" size="mini" @click="() => onOperationType('delete', data)">删除</el-button>
                </template>
                <template v-else>
                  <el-button type="text" size="mini" @click="() => onOperationType('move', data, 0)">移动</el-button>
                  <el-button type="text" size="mini" @click="() => onOperationType('renameLabel', data)">重命名</el-button>
                  <el-button type="text" size="mini" @click="() => onOperationType('deleteLabel', data)">删除</el-button>
                </template>
              </span>
            </span>
    </el-tree>
  </div>
</template>

<script>
export default {
  name: 'labelTree',
  props: {
    typeStr: {
      type: String,
      default: () => ''
    },
    isShowCheckbox: {
      type: Boolean,
      default: () => false
    },
    searchFormObj: { // 搜索数据
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      loading: false,
      filterText: '',
      selectNum: 0,
      selectArr: [],
      selectViewVal: '',
      optionList: [{ title: '程序化标签', isEdit: false }, { title: '自定义标签', isEdit: false }],
      treeData: [{
        name: '程序化标签',
        id: 1,
        isEdit: false,
        tagList: []
      },
      {
        name: '自定义标签',
        id: 2,
        isEdit: false,
        tagList: []
      }]
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        // this.fetchData()
      },
      immediate: true
      // deep: true
    },
    filterText (val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted () {
    this.$nextTick(_ => {})
  },
  created () {
    if (this.typeStr === 'typePage') {
      this.tagGetCustomTagDataList()
    } else {
      this.fetchData()
    }
    // console.log(this.$route.name)
  },
  methods: {
    fetchData () {
      this.loading = true
      const rName = this.$route.name
      const pAncestorsId = this.treeData[0].id
      const cAncestorsId = this.treeData[1].id
      const searchFormObj = this.searchFormObj
      const params = Object.assign({}, searchFormObj)
      // 去除字符串 前后 空格
      for (const item in params) {
        if (typeof params[item] === 'string') {
          params[item] = params[item].trim()
          if (params[item] === '') { delete params[item] }
        }
      }

      this.$api.tagClassifyPageList(params).then((res) => {
        this.loading = false
        if (res.code === 0) {
          const programmingArr = res.data.programmingTags // 程序化标签类型列表
          programmingArr.forEach(it => {
            if (it.tagList) {
              it.tagList.forEach(item => {
                item.ancestorsId = pAncestorsId
              })
            }
          })
          const customArr = res.data.customTags // 自定义标签类型列表
          customArr.forEach(it => {
            if (it.tagList) {
              it.tagList.forEach(item => {
                item.ancestorsId = cAncestorsId
              })
            }
          })
          this.treeData[0].tagList = programmingArr
          this.treeData[1].tagList = customArr
          /*
          if (programmingArr.length > 0) {
            this.treeData[0].tagList = programmingArr
          }
          if (customArr.length > 0) {
            this.treeData[1].tagList = customArr
          }
          */
          if (rName === 'customerInformation') {
            this.treeData.splice(0, 1)
          }
        }
      }).catch((err) => {
        this.loading = false
        console.log(err)
      })
    },
    // 自定义标签数据获取
    tagGetCustomTagDataList () {
      const params = {}
      this.$api.tagGetCustomTagDataList(params).then(res => {
        if (res.code === 0) {
          const resData = res.data
          resData.forEach(item => {
            item.tagList = item.tierList
          })
          this.treeData[1].tagList = resData
          this.treeData.splice(0, 1)
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    onOperationType (method, data, index) {
      // edit-编辑  add-新增分类  move-移动  rename-重名  delete-删除
      let confirmTitle, confirmMessage, messageBox, methodFun
      const buttonConfig = {
        showCancelButton: true, // 是否显示取消按钮
        confirmButtonText: '确定', // 确定按钮的文本内容
        cancelButtonText: '取消', // 取消按钮的文本内容
        confirmButtonClass: 'confirm-button', //	确定按钮的自定义类名
        cancelButtonClass: 'cancel-button', //	取消按钮的文本内容
        customClass: `operation-model ${method}`, // MessageBox 的自定义类名
        closeOnClickModal: false, // 是否可通过点击遮罩关闭 MessageBox
        closeOnPressEscape: false, // 是否可通过按下 ESC 键关闭 MessageBox
        inputValue: data.name, // 输入框的初始文本
        inputErrorMessage: '输入不能为空',
        inputValidator: (value) => { if (!value) { return '输入不能为空' } } // 点击按钮时，对文本框里面的值进行验证
      }
      const params = { createWay: data.id, id: data.id }
      switch (method) {
        case 'edit': // 编辑
          confirmTitle = '编辑'
          // confirmMessage = `是否编辑${data.name}`
          confirmMessage = data.isEdit ? `是否取消编辑${data.name}` : `是否编辑${data.name}`
          messageBox = this.$confirm
          break
        case 'add': // 新增分类
          confirmTitle = '新增分类'
          // confirmMessage = '是否新增分类'
          delete buttonConfig.inputValue // 删除默认值
          messageBox = this.$prompt
          // params.createWay = data.id
          methodFun = this.$api.tagClassifyAdd
          break
        case 'move': // 移动
          confirmTitle = '移动'
          confirmMessage = '是否启用XX'
          messageBox = this.$msgbox
          methodFun = this.$api.tagMoveTag
          break
        case 'rename': // 重命名
          confirmTitle = '重命名'
          confirmMessage = '是否提交当前内容？'
          messageBox = this.$prompt
          delete params.createWay // 删除多余参数
          methodFun = this.$api.tagClassifyUpdateName
          break
        case 'renameLabel': // 重命名 - 标签
          confirmTitle = '重命名'
          confirmMessage = '是否提交当前内容？'
          messageBox = this.$prompt
          methodFun = this.$api.tagUpdateTagName
          break
        case 'delete': // 删除 - 标签
          confirmTitle = '删除'
          confirmMessage = '是否删除分类？'
          messageBox = this.$confirm
          delete params.createWay // 删除多余参数
          methodFun = this.$api.tagClassifyDelete
          break
        case 'deleteLabel': // 删除 - 标签
          confirmTitle = '删除'
          confirmMessage = '是否删除标签？'
          messageBox = this.$confirm
          methodFun = this.$api.tagDelete
          break
        default: // 其它
          console.log('啥都没配置！')
      }
      const h = this.$createElement

      if (method === 'move') {
        const moveConfigTemp = {
          title: '移动',
          message: h('el-select',
            {
              props: { value: this.selectViewVal, filterable: true },
              ref: 'selectView',
              on: {
                change: e => {
                  this.selectViewVal = e
                  // console.log(this.selectViewVal)
                  console.log(e)
                  this.$refs.selectView.value = e // select下拉框值改变，回显到页面上
                }
              }
            }, [
              // this.optionList.map(it => {
              this.treeData[data.ancestorsId - 1].tagList.map(it => {
                return h('el-option', {
                  props: {
                    label: it.name,
                    key: it.id,
                    value: it.id
                  }
                })
              })
            ])
        }
        const moveConfig = Object.assign(moveConfigTemp, buttonConfig)
        messageBox(moveConfig).then(action => {
          console.log(this.selectViewVal)
          params.tagClassifyId = this.selectViewVal
          methodFun(params).then((res) => {
            if (res.code === 0) {
              this.fetchData()
              this.$message({
                type: 'success',
                message: `${confirmTitle}成功！`
              })
            }
          }).catch((err) => {
            console.log(err)
          })
        })
      } else {
        const messageBoxConfigTemp = {
          message: h('div', null, [
            // h('i', { class: 'el-icon-warning', style: 'color:#f90;font-size:30px;' }),
            h('label', { style: 'font-size:18px;line-height:30px;font-weight:600;vertical-align:top;color:#333333;' }, confirmTitle),
            h('p', { style: 'margin:10px 0 0 0;' }, confirmMessage)
          ])
        }
        const messageBoxConfig = Object.assign(messageBoxConfigTemp, buttonConfig)
        messageBox('', messageBoxConfig).then(({ value }) => {
          if (data.isEdit !== undefined) {
            this.treeData[data.id - 1].isEdit = !data.isEdit
            // this.optionList[data.id - 1].isEdit = !data.isEdit
          }
          if (!methodFun) { return }
          if (value) { params.name = value }
          methodFun(params).then((res) => {
            if (res.code === 0) {
              this.fetchData()
              this.$message({
                type: 'success',
                message: `${confirmTitle}成功！`
              })
            }
          }).catch((err) => {
            console.log(err)
          })
        }).catch(() => {
          console.log(`取消${confirmTitle}`)
          this.$message({
            type: 'info',
            message: `取消${confirmTitle}`
          })
        })
      }
    },
    cancelled () {
      this.selectNum = 0
      this.selectArr = []
    },
    addLabel () {
      const tempArr = this.$refs.tree.getCheckedNodes(true, true)
      console.log(tempArr, 'tempArr')
      this.selectArr = tempArr
      this.selectNum = tempArr.length
    },
    filterNode (value, data) {
      if (!value) return true
      console.log(value, data, 'value, data')
      return data.name.indexOf(value) !== -1
    },
    outTree () {
      this.$emit('selectArr', this.selectArr)
      this.selectArr = []
    }
  }
}
</script>
<style scoped lang="scss">
.filter-text{ border-bottom: 20px solid #ffffff;}
:deep(.el-tree-node__content){height: auto;}
  .el-tree{
    padding: 15px;
    background-color: #F4F7FC;
    .el-tree-node{
      .el-tree-node__content{
        .custom-tree-node{
          width: 90%;
          .label-disable {
            color: rgba(243, 63, 63, 1);
          }
          label{
            width: 200px;
            display: inline-block;
            overflow: hidden;
            text-overflow: ellipsis;
            -webkit-line-clamp: 1; /* 可以显示的行数，超出部分用...表示*/
            -webkit-box-orient: vertical;
            a {
              color: #606266;
              text-decoration:none;
            }
          }
          .label-disable {
            a { color: rgba(243, 63, 63, 1); }
          }
          .operation{
            float: right;
            //opacity: 0;
            display: none;
            .el-button{
              color: rgba(65, 104, 231, 1) ;
            }
          }
          .select-num .el-badge{
            font-size: 14px;
            margin-top:0;
            :deep(.el-badge__content){
              top: 10px;
              right: -3px;
            }
          }
        }
        &:hover{
          background-color: #ffffff;
          .custom-tree-node{
            .operation{
              //opacity: 1;
            }
          }
        }
        :deep(&:hover){
          background-color: #ffffff;
          color: rgba(65, 104, 231, 1) ;
        }
      }
    }
    //一级
    :deep(&> .el-tree-node > .el-tree-node__content) {
      height: 40px;
      //line-height: 40px;
      position: relative;
    }
    :deep(&> .el-tree-node > .el-tree-node__content .operation) {display: inline-block!important;}
    :deep(.el-tree-node > .el-tree-node__content .el-checkbox){
      position: absolute;
      right: 15px;
    }
    :deep(&> .el-tree-node > .el-tree-node__content > .el-checkbox) {
      //opacity:0!important;
      display: none!important;
    }
    :deep(&> .el-tree-node > .el-tree-node__children > .el-tree-node > .el-tree-node__content > .el-checkbox) {
      //opacity:0!important;
      display: none!important;
    }
    :deep(&> .el-tree-node > .el-tree-node__content > .custom-tree-node) {
      font-size: 16px;
      .operation{
        //opacity:1!important;
      }
    }
    //二级 、 三级，字号
    :deep(&> .el-tree-node > .el-tree-node__children > .el-tree-node) {
      font-size: 14px;
    }
    :deep(.el-tree-node__expand-icon.el-icon-caret-right){
      font-size: 20px;
      padding: 0;
      margin-top: -5px;
    }
    :deep(.expanded.el-tree-node__expand-icon.el-icon-caret-right){
      color: rgba(65, 104, 231, 1) ;
    }
  }

</style>

<style lang="scss">
//提示框
.operation-model{
  //width: 640px;
  .el-message-box__content{
    .el-message-box__message{
      .el-select{
        width: 100%;
      }
      label{
        display: block;
      }
    }
  }
  .el-message-box__btns{
    .confirm-button, .cancel-button{
      width: 120px;
      height: 36px;
      background-color: rgba(65, 104, 231, 1);
    }
    .confirm-button{
      border: 1px solid rgba(65, 104, 231, 1);
      background-color: rgba(65, 104, 231, 1);
    }
    .cancel-button{
      border: 1px solid rgba(217, 217, 217, 1);
      background-color: rgba(65, 104, 231, 0);
    }
  }
}
//提示框
.operation-model.add {
  .el-message-box__input {
    &:before {
      content: '分类名称';
    }
  }
}
.operation-model.rename {
  .el-message-box__input {
    &:before {
      content: '标签名称';
    }
  }
}

// 编辑按钮
.edit-program{
  &>.el-tree-node{
    &:nth-child(1){
    .el-tree-node__content{
        .custom-tree-node{
          label{ width: 145px; }
         .operation{
           //opacity:1!important;
           display: inline-block!important;
         }
        }
      }
    }
  }
}
.edit-diy{
  &>.el-tree-node{
    &:nth-child(2){
      .el-tree-node__content{
        .custom-tree-node{
          label{ width: 145px; }
          .operation{
            //opacity:1!important;
            display: inline-block!important;
          }
        }
      }
    }
  }
}
</style>
